package com.origin.utils.log;

import android.content.Context;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.RestrictTo;

import com.origin.utils.BuildConfig;
import com.origin.utils.FileUtils;
import com.origin.utils.PathUtils;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


class LogFileUtils {

    private static final Object obj = new Object();


    /**
     *
     */
    public static String initLogSavePath() {
        File logFile = new File(PathUtils.obbPath + "/log");
        File crashFile = new File(PathUtils.obbPath + "/crash");
        if (!crashFile.exists()) {
            if (!crashFile.mkdirs()) {
                Log.e("LogFileUtils", "crashFile 没有创建成功 ");
            }
        }
        if (!logFile.exists()) {
            if (!logFile.mkdirs()) {
                Log.e("LogFileUtils", "logFile 没有创建成功 ");
            }
        }
        logPath = logFile.getAbsolutePath();
        crashPath = crashFile.getAbsolutePath();
        Log.e("App包名", "logPath  " + logPath);
        Log.e("App包名", "crashPath  " + crashPath);
        return logPath;
    }

    private static String logPath = "";
    private static String crashPath = "";
    static ExecutorService cachedThreadPool = Executors.newSingleThreadExecutor();

    public static void writeLogFileExecutorService(final String msg, final String fileName, boolean isCrash) {

        cachedThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                writeLogFile(msg, fileName + ".txt", isCrash);

            }
        });
    }

    private static void writeLogFile(String msg, String fileName, boolean isCrash) {
        if (TextUtils.isEmpty(logPath)) {
            Log.e("LogFileUtils", "日志路径未初始化 请调用 initLogSavePath 初始化");
            return;
        }

        synchronized (obj) {
            try {

                File file;
                if (isCrash) {
                    file = new File(crashPath + "/" + fileName);
                } else {
                    file = new File(logPath + "/" + fileName);
                }
                FileWriter fw;
                if (file.exists()) {
                    // file.length() 单位 bit
                    if (file.length() > LogVariateUtils.getInstance().getFileSize())
                        fw = new FileWriter(file, false);
                    else
                        fw = new FileWriter(file, true);
                } else {
                    fw = new FileWriter(file, false);
                }

                Date d = new Date();
                SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SS", Locale.getDefault());
                String dateStr = s.format(d);

                fw.write(String.format("[%s] %s", dateStr, msg));
                if (msg.contains("┹")) {
                    fw.write("\r\n");
                }
                fw.write(13);
                fw.write(10);
                fw.flush();
                fw.close();
//                Log.e("LogFileUtils", "writeLogFile 写入成功 "+file.getAbsolutePath() );
            } catch (Throwable ex) {
                ex.printStackTrace();
//                Log.e("LogFileUtils", "writeLogFile 1 异常 " + ex);
            }
        }
    }

    /**
     * 取出文件
     *
     * @return
     */
    public static String readLogText(String filePathName) {
        FileReader fr = null;
        try {
            File file = new File(filePathName);
            if (!file.exists()) {
                return "";
            }
            long n = LogVariateUtils.getInstance().getFileSize();
            long len = file.length();
            long skip = len - n;
            fr = new FileReader(file);
            fr.skip(Math.max(0, skip));
            char[] cs = new char[(int) Math.min(len, n)];
            fr.read(cs);
            return new String(cs).trim();
        } catch (Throwable ex) {
            Log.e("LogFileUtils", "readLogText 1 异常 " + ex);
            ex.printStackTrace();
        } finally {
            try {
                if (fr != null)
                    fr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "";
    }

}
